package com.jsmtr.rms.service.impl;

import com.jsmtr.rms.dao.DaoService;
import com.jsmtr.rms.entity.BaseUser;
import com.jsmtr.rms.entity.KnowManage;
import com.jsmtr.rms.entity.Knowledge;
import com.jsmtr.rms.service.IKnowledgeManageService;
import com.jsmtr.rms.utils.RightInterceptor;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author wyh
 */
@Service
public class KnowledgeManageServiceImpl implements IKnowledgeManageService {
    @Resource
    DaoService dao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    @SuppressWarnings("rawtypes")
    public Map<String, Object> getKnowledgePointList(int page, int limit, Map<String, Object> search) throws Exception {
        String knowledgeId;
        String name;
        String key;


        String hql =  "select know,km.name from Knowledge know, KnowManage km where know.kid=km.id ";
        String countHql = "select count(*) from Knowledge know, KnowManage km where know.kid=km.id ";

        Map<String, Object> params = new HashMap<>(1);

        //根据KnowManager Id查询
        try {
            knowledgeId = (String) search.get("knowManagerId");
            if (knowledgeId == null) {
                knowledgeId = (String) search.get("zid");
            }
            String suffix = " and kid=:id";
            if (knowledgeId != null && !knowledgeId.isEmpty()) {
                hql += suffix;
                countHql += suffix;
                params.put("id", knowledgeId);
            }
        } catch (NullPointerException ignored) {
        }

        //根据岗位名name查询
        try {
            name = (String) search.get("name");
            String suffix = " and name=:name";
            if (name != null && !name.isEmpty()) {
                hql += suffix;
                countHql += suffix;
                params.put("name", name);
            }
        } catch (NullPointerException ignored) {
        }

        //根据关键字key查询
        try {
            key = (String) search.get("key");
            String suffix = " and concat(km.path,km.name) like :key";
            if (key != null && !key.isEmpty()) {
                hql += suffix;
                countHql += suffix;
                params.put("key", "%" + key + "%");
            }
        } catch (NullPointerException ignored) {
        }


        Long count = (Long) dao.findUnique(countHql, params);
        List knowledges = dao.findLimit(hql, params,(page - 1) * limit, limit);
        Map<String, Object> retVal = new HashMap<>(2);
        retVal.put("data", knowledges);
        retVal.put("count", count);
        return retVal;
    }

    final public static String DISABLED = "disabled";
    final public static String ENABLED = "enabled";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addKnowledge(List<Knowledge> knowledge, String knowledgeName, String position, HttpServletRequest request) {
        try {
            KnowManage knowManage = (KnowManage) dao.findFirst("from KnowManage where name=:name", "name", knowledgeName);
            if (knowManage == null) {
                BaseUser baseUser = (BaseUser) request.getSession().getAttribute(RightInterceptor.SEESION_MEMBER);
                knowManage = new KnowManage();
                knowManage.setName(knowledgeName);
                knowManage.setAddName(baseUser.getUname());
                knowManage.setAddDate(new Date());
                knowManage.setModifyname(baseUser.getUname());
                knowManage.setModifyDate(new Date());
                knowManage.setState(DISABLED);
                knowManage.setPath(position);
                dao.add(knowManage);
            }

            final String knowManageId = knowManage.getId();
            knowledge.forEach(know->know.setKid(knowManageId));
            dao.addAll(knowledge);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean editKnowledge(List<Knowledge> knowledge, String knowledgeName, String position) {
        try {
            String hql = "from KnowManage where name=:name";
            Map<String, Object> params = new HashMap<>();
            params.put("name", knowledgeName);
            KnowManage knowManage = (KnowManage)dao.findUnique(hql, params);
            String kid = Objects.requireNonNull(knowManage).getId();
            params.put("kid", kid);
            String deleteHql = "delete Knowledge where kid=:kid";
            params.remove("name");
            knowledge.forEach(value->value.setKid(kid));
            dao.executeHQL(deleteHql, params);
            dao.addAll(knowledge);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean enableKnowledge(String knowledgeId, String knowledgeState, HttpServletRequest request) {
        try {
            BaseUser baseUser = (BaseUser) request.getSession().getAttribute(RightInterceptor.SEESION_MEMBER);
            String hql = "update KnowManage set state=:state,modifyDate=:mdate,modifyName=:mname where id=:id";
            Map<String, Object> params = new HashMap<>(4);
            params.put("state", knowledgeState);
            params.put("mdate",new Date());
            params.put("mname",baseUser.getUname());
            params.put("id",knowledgeId);
            int effected = dao.executeHQL(hql,params);
            return effected > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteKnowledge(String id) {
        try {
            if (id == null || id.isEmpty()) {
                return false;
            }
            Map<String, Object> params = new HashMap<>(1);
            params.put("id", id);
            String delKnowManager = "delete KnowManage where id=:id";
            String delKnowledge = "delete Knowledge where kid=:id";
            dao.executeHQL(delKnowManager, params);
            dao.executeHQL(delKnowledge, params);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> getKnowledgeList(int page, int limit, String position, String knowledgeState, String keyWord,
                                                String orderKey, String orderType) throws Exception {
        String hql = " from KnowManage where 1=1";
        String countHql = "select count(*) from KnowManage where 1=1 ";
//        String positionSuffix = " and path like '%:position%'";
        String stateSuffix = " and state = :state";
        String keywordSuffix = " and CONCAT(COALESCE(name,''),COALESCE(addName, ''),COALESCE(modifyName, ''),COALESCE(modifyDate,'')," +
                "COALESCE(state,''),COALESCE(path,'')) like :keyword";
        String orderSuffix = " order by ";
        Map<String, Object> params = new HashMap<>(3);
//        if (StringUtils.isNotBlank(position)) {
//            hql += positionSuffix;
//            countHql += positionSuffix;
//            params.put("position", position);
//        }
        if (StringUtils.isNotBlank(knowledgeState)) {
            hql += stateSuffix;
            countHql += stateSuffix;
            params.put("state", knowledgeState);
        }
        if (StringUtils.isNotBlank(keyWord)) {
            hql += keywordSuffix;
            countHql += keywordSuffix;
            params.put("keyword", "%" + keyWord + "%");
        }
        if (StringUtils.isNotBlank(orderKey) && StringUtils.isNotBlank(orderType)) {
            hql += orderSuffix + orderKey + " " + orderType;
        }
        Map<String, Object> stringObjectMap = new HashMap<>(2);
        Long count = (Long) dao.findUnique(countHql, params);
        Object data = dao.findLimit(hql, params, (page - 1) * limit, limit);
        stringObjectMap.put("count", count);
        stringObjectMap.put("data", data);
        return stringObjectMap;
    }

    @Override
    @SuppressWarnings("rawtypes")
    public List getJobs() throws Exception {
        String sql = "select distinct job.name, job.id  from KNOWLEDGE know left join BASE_JOB job on job.NAME=know.NAME";
        return dao.executeSQLQuery(sql);
    }

    public void setDao(DaoService dao) {
        this.dao = dao;
    }
}
